# -*- coding:utf-8 -*-
from typing import List, Any


class CaesarCipher:
    """可加密解密的凯撒密码类"""

    def __init__(self, shift: int):
        encoder_upper = [""] * 26
        encoder_lower = [""] * 26
        decoder_upper = [""] * 26
        decoder_lower = [""] * 26
        for i in range(26):
            encoder_upper[i] = chr((i + shift) % 26 + ord("A"))
            encoder_lower[i] = chr((i + shift) % 26 + ord("a"))
            decoder_upper[i] = chr((i - shift) % 26 + ord("A"))
            decoder_lower[i] = chr((i - shift) % 26 + ord("a"))
        """
        就算是需要转换小写字母也可以不需要_forward/backward_lower；
        可以把小写转换为大写在大写表中转换后再转换为小写；
        但是感觉这么做代码变复杂了故没有这么去考虑
        """
        self._forward_upper = "".join(encoder_upper)
        self._forward_lower = "".join(encoder_lower)
        self._backward_upper = "".join(decoder_upper)
        self._backward_lower = "".join(decoder_lower)

    def encrypt(self, message):
        return self._transform(message, self._forward_upper, self._forward_lower)

    def decrypt(self, secret):
        return self._transform(secret, self._backward_upper, self._backward_lower)

    @staticmethod
    def _transform(text, coder_upper, coder_lower):
        txt: List[Any] = list(text)
        for i in range(len(txt)):
            if txt[i].isupper():
                j = ord(txt[i]) - ord("A")
                txt[i] = coder_upper[j]
            elif txt[i].islower():
                j = ord(txt[i]) - ord("a")
                txt[i] = coder_lower[j]
        return "".join(txt)
